#include <stdio.h>
#include "esp_log.h"
#include "mymqtt.h"
#include "mqtt_protocol.h"

static const char *TAG = "MQTT_EXAMPLE";

String MqttTopicsDown;
String MqttTopicsUp;

#define CONFIG_BROKER_URI "mqtts://10.177.2.200:8883"

static const uint8_t mqtt_pem[]  = 
"-----BEGIN CERTIFICATE-----\nMIIDxzCCAq8CFBAIng+DGaZ/ZPEVL1SxpGppJzeLMA0GCSqGSIb3DQEBCwUAMIGf\
MQswCQYDVQQGEwJDTjESMBAGA1UECAwJR3Vhbmdkb25nMREwDwYDVQQHDAhTaGVu\
emhlbjEYMBYGA1UECgwPRXhhbXBsZSBDb21wYW55MRYwFAYDVQQLDA1JVCBEZXBh\
cnRtZW50MRUwEwYDVQQDDAwxMC4xNzcuMi4yMDAxIDAeBgkqhkiG9w0BCQEWEWFk\
bWluQGV4YW1wbGUuY29tMB4XDTI1MDMyNDEzNTAwM1oXDTI2MDMyNDEzNTAwM1ow\
gZ8xCzAJBgNVBAYTAkNOMRIwEAYDVQQIDAlHdWFuZ2RvbmcxETAPBgNVBAcMCFNo\
ZW56aGVuMRgwFgYDVQQKDA9FeGFtcGxlIENvbXBhbnkxFjAUBgNVBAsMDUlUIERl\
cGFydG1lbnQxFTATBgNVBAMMDDEwLjE3Ny4yLjIwMDEgMB4GCSqGSIb3DQEJARYR\
YWRtaW5AZXhhbXBsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\
AQDQ8ZfnF6L/lXu2l5En4ursESnrACKqVq76UUiwqHGe5/Lv0utMGxM88hAunG2+\
S4yOcJedXoyvFLl9HqOxRxRohlk/yq41pfc3QVHK0n+xfHJ3vHsBcjjzm2bWZfF4\
flG+stpzg81tYrRkqAGTEV5Tnbw7vsbfqXRFXvasZovb8hbr57oeXGfMufITtTVZ\
braunDNU3vVQdTsbdLNk9ST8qqRjWNb5uDih1kytMRil3J1LO4C3ybceaJrNcqDj\
Drn88LkaPhkkdytGImBJ6mkIogfz/DPjquLwME+Fz7wJBdq6hyu/G2WNfU22d1Oo\
HlKnfucdd7r7GzOq71xGGBvNAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAClQ6YYv\
FjLPBUSsNoMpszFypxrH+pHxgx16zsx+LlJo5l3Va8v7leYxni8IpPRBuoPHd6oU\
gVIFm7ra1bKrDv42Xx2b26bzVCjkcGVXmuY+p0sj78Mdg3YdxxlJdo76ckMah2n3\
J4NqzrKPYfRXo/ONMH2H13uUtd9V1bQpm4VeZwyZpTb3xy9/vhCaI41Jl0tcGtHI\
hlk1gIvBjHDiQtNILHD2NcDmRMY7KhiNJY4WiKpONDCNtUfUVt9ukRO0YKZeDmFy\
Y4aKk9Onkfca10zocfZRi+i+7/MKMcX77cgnlIdDpWaqbDN9w7lu54xNduMXMmu9\
f23UjROj1aLeDZk=\n-----END CERTIFICATE-----";

/*
 * @brief Event handler registered to receive MQTT events
 *
 *  This function is called by the MQTT client event loop.
 *
 * @param handler_args user data registered to the event.
 * @param base Event base for the handler(always MQTT Base in this example).
 * @param event_id The id for the received event.
 * @param event_data The data for the event, esp_mqtt_event_handle_t.
 */
static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data)
{
    ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%" PRIi32, base, event_id);
    esp_mqtt_event_handle_t event = (esp_mqtt_event_handle_t)event_data;
    esp_mqtt_client_handle_t client = event->client;
    int msg_id;
    switch ((esp_mqtt_event_id_t)event_id) {
    case MQTT_EVENT_CONNECTED:
        ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
        msg_id = esp_mqtt_client_subscribe(client, MqttTopicsDown.c_str(), 0);
        ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);

        break;
    case MQTT_EVENT_DISCONNECTED:
        ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
        break;

    case MQTT_EVENT_SUBSCRIBED:
        ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
        msg_id = esp_mqtt_client_publish(client, "/topic/qos0", "data", 0, 0, 0);
        ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
        break;
    case MQTT_EVENT_UNSUBSCRIBED:
        ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
        break;
    case MQTT_EVENT_PUBLISHED:
        ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
        break;
    case MQTT_EVENT_DATA:
        ESP_LOGI(TAG, "MQTT_EVENT_DATA");
        on_topic_msg_down(event);
        break;
    case MQTT_EVENT_ERROR:
        ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
        if (event->error_handle->error_type == MQTT_ERROR_TYPE_TCP_TRANSPORT) {
            ESP_LOGI(TAG, "Last error code reported from esp-tls: 0x%x", event->error_handle->esp_tls_last_esp_err);
            ESP_LOGI(TAG, "Last tls stack error number: 0x%x", event->error_handle->esp_tls_stack_err);
            ESP_LOGI(TAG, "Last captured errno : %d (%s)",  event->error_handle->esp_transport_sock_errno,
                     strerror(event->error_handle->esp_transport_sock_errno));
        } else if (event->error_handle->error_type == MQTT_ERROR_TYPE_CONNECTION_REFUSED) {
            ESP_LOGI(TAG, "Connection refused error: 0x%x", event->error_handle->connect_return_code);
        } else {
            ESP_LOGW(TAG, "Unknown error type: 0x%x", event->error_handle->error_type);
        }
        break;
    default:
        ESP_LOGI(TAG, "Other event id:%d", event->event_id);
        break;
    }
}
#include "config.h"

char mqtt_uri[128] = {0};
char mqtt_username[128] = {0};
char mqtt_pwd[128] = {0};
void mqtt_app_start(void)
{

    MqttTopicsUp = "/atp/up";
    MqttTopicsDown = "/atp/down";
    memcpy(mqtt_uri,config.get_mqtt_url().c_str(),config.get_mqtt_url().length());
    memcpy(mqtt_username,config.get_mqtt_name().c_str(),config.get_mqtt_name().length());
    memcpy(mqtt_pwd,config.get_mqtt_pwd().c_str(),config.get_mqtt_pwd().length());
    ESP_LOGI(TAG,"USER:%s",mqtt_username);
    ESP_LOGI(TAG,"PWD:%s",mqtt_pwd);
    
    esp_mqtt_client_config_t mqtt_cfg = {0};
    mqtt_cfg.broker.address.uri = mqtt_uri;
    mqtt_cfg.broker.verification.certificate = (const char *)mqtt_pem;
    mqtt_cfg.credentials.username = mqtt_username;
    mqtt_cfg.credentials.authentication.password = mqtt_pwd;
    mqtt_cfg.task.stack_size = 1024*15;
    mqtt_cfg.buffer.size = 1024*3;
    ESP_LOGI(TAG, "[APP] Free memory: %" PRIu32 " bytes", esp_get_free_heap_size());
    esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);

    /* The last argument may be used to pass data to the event handler, in this example mqtt_event_handler */
    esp_mqtt_client_register_event(client, (esp_mqtt_event_id_t)ESP_EVENT_ANY_ID, mqtt_event_handler, NULL);
    esp_mqtt_client_start(client);
}


